﻿import mx.utils.Delegate;
/**
 * ...
 * @author	Kliment
 * @version	1.2.0
 */

class kliment.utils.Queue {
	private var _queue:Array;
	private var _loading:Number = 0;
	
	public var onItemStart:Function;
	public var onItemComplete:Function;
	public var onTotalComplete:Function;
	//public var onItemError:Function;
	
	public var onStart:Function;
	public var onComplete:Function;
	//public var onError:Function;

	
	public function Queue() {
		_queue = new Array();
	}
	
	public function add(target:Object, onStart:Function):Function {
		_queue.push({target:target, onStart:onStart});
		
		return Delegate.create(this, next);
	}
	
	public function next():Void {
		onItemComplete();
		_loading++;
		_next();
	}
	
	private function _next():Void {
		if (_loading < _queue.length) {
			_queue[_loading].onStart();
			onItemStart();
		} else {
			onTotalComplete();
		}
	}
	
	public function start():Void {
		_loading = 0;
		if (_queue.length > 0){
			_next();
			onStart();
		}
	}
	
	public function reset():Void {
		_loading = 0;
		_queue = new Array();
		onComplete();
	}
	
	public function get length():Number { return _queue.length }
	
	public function get current():Number { return _loading }
		
	public function get currentItem():Object { return _queue[_loading] }
}